﻿using UnityEngine;
using System.Collections;

namespace View
{
    public class SplitterParticle
    {

        private int seed;
        private float radius = 0.025f;
        private Vector2 startPos;
        private Vector2 position;
        private Vector2 velocity;
        private Vector2 acceleration;
        private float elapsedTime;
        private float lifeTime;

        private float ratio;

        public SplitterParticle(int seed, Vector2 startPos, float ratio)
        {
            this.seed = seed;
            this.startPos = startPos;
            this.radius *= ratio;
            this.ratio = ratio;
            this.lifeTime = 5.0f;
            this.acceleration = new Vector2(0.0f * ratio, 3f * ratio);
            setUpParticle();
        }

        private void setUpParticle()
        {
            this.position = new Vector2(startPos.x, startPos.y);

            System.Random rand = new System.Random(this.seed);
            this.velocity = new Vector2(((float)rand.NextDouble() - 0.5f) * ratio, ((float)rand.NextDouble() - 0.5f) * ratio);
            // normalize to get it spherical vector with length 1.0
            this.velocity.Normalize();
            // add random length between 0 to maxSpeed
            float maxSpeed = 2.0f * ratio;
            float minSpeed = 0.1f * ratio;
            this.velocity *= minSpeed + (float)rand.NextDouble() * (maxSpeed - minSpeed);
        }

        // Update is called once per frame
        public void Update()
        {
            if (elapsedTime < lifeTime)
            {
                elapsedTime += Time.deltaTime;
                velocity.x = Time.deltaTime * acceleration.x + velocity.x;
                velocity.y = Time.deltaTime * acceleration.y + velocity.y;

                position.x += Time.deltaTime * velocity.x;
                position.y += Time.deltaTime * velocity.y;
            }
            else
            {
                //elapsedTime = 0;
                //setUpParticle();
            }

        }

        public void OnGUI(Texture2D texture, GameCamera cam)
        {
            Vector2 visualPos = cam.getVisualCoordinates(position);
            Vector2 visualSize = cam.getVisualSizeWithRadius(radius);
            GUI.DrawTexture(new Rect(visualPos.x - visualSize.x / 2, visualPos.y - visualSize.y / 2, visualSize.x, visualSize.y), texture);
        }
    }
}
